package com.aaa.javaweb.servlet;

import com.aaa.javaweb.dao.impl.SheShiDaoimpl;
import com.aaa.javaweb.entity.SheShi;
import com.aaa.javaweb.until.TransBean;
import com.alibaba.fastjson.JSON;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@WebServlet("/sheshi")
public class SheShiContorller extends HttpServlet {

    SheShiDaoimpl ssdl = new SheShiDaoimpl();
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        resp.setContentType("text/html; charset=UTF-8");

        String method = req.getParameter("method");
        if (method!=null){
            switch (method){
                case "del":
                    this.del(req,resp);
                    break;
                case "add":
                    this.add(req,resp);
                break;
            }

        }else {
            List<Map> maps = ssdl.selectALL();
            Map map = new HashMap();
            map.put("code",0);
            map.put("msg","");
            map.put("count",maps.size());
            map.put("data",maps);
            String s = JSON.toJSONString(map);
            PrintWriter writer = resp.getWriter();
            writer.print(s);
            writer.flush();
            writer.close();

        }

    }



    private void add(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        req.setCharacterEncoding("utf-8");
        resp.setContentType("text/html; charset=UTF-8");
        Map<String, String[]> parameterMap = req.getParameterMap();
        parameterMap.forEach((x,y)->{
            System.out.println(x+" "+ Arrays.toString(y));
        });
        SheShi sheShi = new SheShi();
        TransBean.populate(sheShi,parameterMap);
        System.out.println(sheShi);
        int addone = ssdl.addone(sheShi);
        resp.sendRedirect("yzruser/Sheshishow.jsp");
    }

    private void del(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String gid = req.getParameter("gid");
        int delone = ssdl.delone(gid);
        if (delone>0){
           resp.sendRedirect("yzruser/Sheshishow.jsp");
        }
    }
}
